package cc.vant.wechat.model.packet;


import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.util.CharsetUtil;

/**
 * TODO:想提高效率可以用Pooled 方式重写
 * 协议设计为前4个字节为类型,再4个字节代表用户名长度(字节为单位),再分别为用户名以及密码
 *
 * @author Vant
 * @version 2018/11/20 下午 2:16
 */
public abstract class UserInfoPacket implements Packet {
    private String userName;
    private String password;

    public UserInfoPacket() {
    }

    public UserInfoPacket(String userName, String password) {
        this.userName = userName;
        this.password = password;
    }

    public ByteBuf serialize() {
        ByteBuf buffer = Unpooled.buffer(32);

        //type
        buffer.writeInt(getType());

        //len
        byte[] bytes = userName.getBytes(CharsetUtil.UTF_8);
        buffer.writeInt(bytes.length);

        //name
        buffer.writeBytes(bytes);

        //password
        buffer.writeCharSequence(password, CharsetUtil.UTF_8);

        return buffer;
    }

    public void unserialize(ByteBuf data) {
        data.skipBytes(4);
        int length = data.readInt();
        userName = data.readBytes(length).toString(CharsetUtil.UTF_8);
        password = data.readBytes(data.readableBytes()).toString(CharsetUtil.UTF_8);
    }

    @Override
    public abstract int getType();

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}